package UIFree
{
	import UIUtils.uif_color;
	import UIUtils.union;
	
	public class FXContainer extends FX {
		private var _completeFunc: Function;
		public static const COLORPROPERTYS: Array = ['colors', 'color', 'line_color', 'fill_color'];
		
		public function FXContainer(a_component: Object, propertyName: String, a_from: *, a_to:*, 
								completeFunc: Function=null, a_transition: Function=null, fps: int=16, duration: int=500) {
			super(function(delta: Number): void {
				a_component[propertyName] = fxCompute(a_from, a_to, delta);
			}, a_transition, fps, duration);
			_completeFunc = completeFunc;
			if (_completeFunc != null) addEventListener(FXEvent.COMPLETE, _completeFunc);
		}
	
		public static function fxCompute(a_from: *, a_to: *, a_delta: Number, asColor: Boolean = false): * {
			if ((a_from is Boolean) && (a_to is Boolean)) {
				return a_delta<0.5?a_from:a_to;
			} else if ((a_from is Number) && (a_to is Number)) {
				if (asColor) return uif_color.computeRGBA(a_from, a_to, a_delta);
				else return (a_to - a_from) * a_delta + a_from;
			} else if ((a_from is String) && (a_to is String))
				return a_delta<0.5?a_from:a_to;
			else  if ((a_from is Array) && (a_to is Array))
				return fxComputeArray(a_from, a_to, a_delta, asColor);
			else  if ((a_from is Object) && (a_to is Object))
				return fxComputeObject(a_from, a_to, a_delta, asColor);
			else return null;
		}
		
		public static function fxComputeObject(a_from: Object, a_to: Object, a_delta: Number, asColor: Boolean = false): Object {
			var result: Object = union.apply(a_from, {});
			for (var i: String in a_to) {
				if (a_from.hasOwnProperty(i) && (a_from[i] != a_to[i])) {
					result[i] = fxCompute(a_from[i], a_to[i], a_delta, 
						((COLORPROPERTYS.indexOf(i) > -1) && (!a_from[i].hasOwnProperty('colors'))) || asColor);
				}
			}
			return result;
		}
		
		public static function fxComputeArray(a_from: Array, a_to: Array, a_delta: Number, asColor: Boolean = false): Array {
			var result: Array = a_from.concat();
			for (var i: uint=0; i<a_to.length; i++) {
				result[i] = fxCompute(a_from[i], a_to[i], a_delta, asColor);
			}
			return result;
		}

		override public function dispose(): void {
			if (_completeFunc != null) removeEventListener(FXEvent.COMPLETE, _completeFunc);
			super.dispose();
		}

		override public function cancel(): void {
			super.cancel();
			dispose();
		}
	}
}